<template>
  <div>
    <BasicTable @register="registerTable" @resize-column="handleResizeColumn">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增 </a-button>
        <a-button type="primary" @click="handleImport"> 导入 </a-button>
        <a-button type="primary" @click="handleExport" :loading="isDownload"> 导出 </a-button>
        <a-button type="primary" @click="handleMoreDelete"> 删除 </a-button>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'clarity:media-changer-outline-alerted',
              tooltip: '设计',
              onClick: handleDesign.bind(null, record),
            },
            // {
            //   icon: 'clarity:details-line',
            //   tooltip: '设计',
            //   onClick: handleDesignUeditor.bind(null, record),
            // },
            {
              icon: 'clarity:view-list-line',
              tooltip: '视图',
              onClick: handleFormView.bind(null, record),
            },
            // {
            //   icon: 'ant-design:setting-outlined',
            //   tooltip: '管理',
            //   onClick: handleUEditForm.bind(null, record),
            // },
            {
              icon: 'codicon:file-submodule',
              tooltip: '模块',
              onClick: handleModule.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'topRight',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <FormManagementDrawer @register="registerDrawer" @success="handleSuccess" />
    <FormManagementFileModal
      @register="registerFormManagementFileModal"
      @success="handleSuccessFormManagementFileModal"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, h, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import FormManagementDrawer from './FormManagementDrawer.vue';
  import FormManagementFileModal from './modules/FormManagementFileModal.vue';
  import { exportSolution } from '/@/api/flowManage/flowManage';

  import { useModal } from '/@/components/Modal';
  import { columns, searchFormSchema } from './formManagement.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useRouter } from 'vue-router';
  import { useGo } from '/@/hooks/web/usePage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { downloadByData } from '/@/utils/file/download';

  import { getFormListForm, getFormDel } from '/@/api/formDesign/formDesign';
  export default defineComponent({
    name: 'FormManagement',
    components: {
      BasicTable,
      FormManagementDrawer,
      TableAction,
      FormManagementFileModal,
    },
    setup() {
      const { t } = useI18n();
      const { resolve } = useRouter();
      const { createMessage, createConfirm } = useMessage();
      const [registerDrawer, { openDrawer }] = useDrawer();

      const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys, getForm }] = useTable({
        title: '表单管理',
        api: getFormListForm,
        columns,
        formConfig: {
          labelWidth: 150,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        searchInfo: {
          op: 'search',
        }, //额外的参数
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        clickToRowSelect: false,
        indexColumnProps: { width: 50 },
        showIndexColumn: false,
        beforeFetch: (info) => {
          let newInfo = info;
          return newInfo;
        },
        rowKey: 'code',
        rowSelection: {
          type: 'checkbox',
        },
        actionColumn: {
          width: 220,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });
      const go = useGo();

      function handleCreate() {
        const { getFieldsValue } = getForm();
        const data = getFieldsValue();
        let record: any = {};
        console.log('data', data);
        if (data.isFlow) {
          record.isFlow = data.isFlow;
        }
        openDrawer(true, {
          isUpdate: false,
          record,
        });
      }

      function handleEdit(record: Recordable) {
        if (true) {
          const params = {
            record: record,
            isUpdate: true,
          };
          go({
            path: '/formManagementEdit',
            query: {
              info: JSON.stringify(params),
              title: `${record.name ? record.name : ''}编辑`,
              cacheName: `formManagementEdit${record['code']}`,
            },
          });
        } else {
          openDrawer(true, {
            record,
            isUpdate: true,
          });
        }
      }

      const handleMoreDelete = () => {
        const selectRowKeys = getSelectRowKeys();
        if (selectRowKeys.length == 0) {
          return createMessage.warning('请选择数据');
        }
        const codes = selectRowKeys.join(',');
        deleteAction(codes);
      };

      const handleDelete = async (record: Recordable) => {
        try {
          await getFormDel({ codes: record.code });
          createMessage.success('操作成功');
          handleSuccess();
        } catch (error) {
          console.error('handleDelete', error);
        }
      };

      const deleteAction = (codes) => {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要删除么'),
          onOk: async () => {
            try {
              const params = {
                codes,
              };
              await getFormDel(params);
              createMessage.success('操作成功');
              handleSuccess();
            } catch (err) {
              console.error(err);
            } finally {
            }
          },
        });
      };

      function handleSuccess() {
        setSelectedRowKeys([]);
        reload();
      }

      const handleDesign = (record) => {
        // let routeUrl: any = {};
        // routeUrl = resolve({
        //   path: '/formDesigner',
        //   query: {
        //     formCode: record.code,
        //   },
        // });
        // const height = screen.height;
        // const width = screen.width;
        // window.open(
        //   routeUrl.href,
        //   '',
        //   `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
        // );

        let routeUrl: any = {};
        routeUrl = resolve({
          path: '/formEditor',
          query: {
            formCode: record.code,
            pageName: record.name,
            // name: formRowData.value.cwsWorkflowTitle,
            // token: getToken() as any,
          },
        });
        const height = screen.height;
        const width = screen.width;
        window.open(
          routeUrl.href,
          '',
          `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
        );
      };
      //ueditor design
      const handleDesignUeditor = (record) => {
        let routeUrl: any = {};
        routeUrl = resolve({
          path: '/ueditorFormDesigner',
          query: {
            formCode: record.code,
          },
        });
        const height = screen.height;
        const width = screen.width;
        window.open(
          routeUrl.href,
          '',
          `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
        );
      };
      const handleFormView = (record) => {
        go({
          path: '/formView',
          query: {
            id: record.id,
            title: record.name,
            formCode: record.code,
            cacheName: `formView${record['code']}`,
          },
        });
      };

      const handleUEditForm = (record) => {
        go({
          path: '/formEdit',
          query: {
            urlParams: '/admin/form_edit.jsp?code=' + record?.code,
          },
        });
      };

      //打开模块
      const handleModule = (record) => {
        go({
          path: '/formModule',
          query: {
            id: record.id,
            formCode: record?.code,
            title: record?.name,
            cacheName: `formModule${record['code']}`,
          },
        });
      };

      const [registerFormManagementFileModal, { openModal }] = useModal();
      const handleImport = () => {
        openModal(true, {});
      };
      //导入回调
      const handleSuccessFormManagementFileModal = () => {
        handleSuccess();
      };

      const isDownload = ref(false);
      const handleExport = () => {
        const selectRowKeys = getSelectRowKeys();
        if (selectRowKeys.length == 0) {
          return createMessage.warning('请选择数据');
        }
        const codes = selectRowKeys.join(',');

        isDownload.value = true;
        exportSolution({ codes: codes }).then((data) => {
          isDownload.value = false;
          let title = '解决方案';
          if (data) {
            downloadByData(data, `${title}.txt`);
          }
        });
      };

      return {
        registerTable,
        registerDrawer,
        handleCreate,
        handleEdit,
        handleMoreDelete,
        handleDelete,
        handleSuccess,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        handleDesign,
        handleDesignUeditor,
        handleFormView,
        handleUEditForm,
        handleImport,
        handleExport,
        registerFormManagementFileModal,
        handleSuccessFormManagementFileModal,
        handleModule,
        isDownload,
      };
    },
  });
</script>
